package com.app.controller.backstage;

import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Slf4j
@Controller
@RestController
@RequestMapping("/jtwq")
public class AdminUploadController {
    @Autowired
    UserService userService;


    /**
     * 上传文件
     */
    @PostMapping("/uploadBack")
    public Result<String> upload(HttpServletRequest request,
                                 @RequestParam("file") MultipartFile file) throws IOException {

        if(!file.isEmpty()){
            //上传文件路径
            String path = "";
            path= SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            //获取文件的后缀名
            String suffix = fileName.substring(lastIndexOf);

            File filePath = new File(path + File.separator + date+suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if(!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            String imgURL = "";
            //szjy.gshwsc.com  域名
            imgURL =  SystemConstant.DEFAULT_UPLOAD_SERVICE_URL+date+suffix;
            log.info("地址"+imgURL);
            return Result.success(imgURL);
        }else{
            return Result.error(500,"上传失败");
        }

    }

    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(3);
            long result=0;
            switch(number){
                case 0:
                    result=Math.round(Math.random()*25+65);
                    sb.append(String.valueOf((char)result));
                    break;
                case 1:
                    result=Math.round(Math.random()*25+97);
                    sb.append(String.valueOf((char)result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }
}
